import type { MyWebSocket } from "@/interface/store";
import type { Request } from "express";
import { webSocketLogger, logger } from "@/utils/log";
import { sendWs_util, sendWs_id_util, sendWs_all_util } from "@/utils/utils";
import { JWT } from "@/utils/JWT";
import type { KeyStringAny } from "@/interface/global";

export const wechaty = (ws: MyWebSocket, req: Request) => {
  const protocol = req.headers["sec-websocket-protocol"]?.split(", ") || [];
  const header: KeyStringAny<string> = {};

  // 获取请求头
  for (let i = 0; i < protocol?.length; i += 2) {
    header[protocol[i]] = protocol[i + 1];
  }

  // 权限校验
  try {
    // if (!JWT.verify(header.token.toString())) {
    //   sendWs_util(ws, {}, "请重新登录", 202);
    //   ws.close();
    // } else {
    //   sendWs_util(ws, {}, "连接成功", 203);
    // }
  } catch (err) {
    // sendWs_util(ws, {}, "请先登录", 202);
    // ws.close();
  }

  logger.info(0, "WebSocket已连接");

  // const id = header.token.toString();
  // ws.id = id;

  // webSocketLogger.warn(`进 ${id}`);

  ws.on("message", (msg: any) => {
    // webSocketLogger.info(`收 ${id} ${msg}`);
    webSocketLogger.info(`收： ${msg}`)

    // 发送
    // sendWs_util(ws, msg + "123");
    // sendWs_id_util(ws.id,msg+'123')
    sendWs_all_util('一起来')
  });

  ws.on("close", (mevt: any) => {
    webSocketLogger.warn(`退 ${ws.id}`);
  });
};
